package com.taoym.voucher.xcx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taoym.voucher.common.constant.CommonConstant;
import com.taoym.voucher.common.enums.ActivityPlatformEnum;
import com.taoym.voucher.common.utils.HttpClientUtils;
import com.taoym.voucher.common.utils.ThreadLocalUtils;
import com.taoym.voucher.common.utils.ThreadPoolUtils;
import com.taoym.voucher.xcx.callables.ActGenerateCallable;
import com.taoym.voucher.xcx.domain.XcxPromotion;
import com.taoym.voucher.xcx.entity.dto.XcxGetMtYouXuanDTO;
import com.taoym.voucher.xcx.entity.vo.XcxGetMtYouXuanResp;
import com.taoym.voucher.xcx.entity.vo.XcxGetPromotionVO;
import com.taoym.voucher.xcx.mapper.XcxActivityMapper;
import com.taoym.voucher.xcx.mapper.XcxPromotionMapper;
import com.taoym.voucher.xcx.service.SysUserService;
import com.taoym.voucher.xcx.service.XcxPromotionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

/**
 * @coder taoym
 * @datetime 2021/6/7 10:21
 * @desc
 */
@Service
public class XcxPromotionServiceImpl implements XcxPromotionService {

    @Resource
    private XcxActivityMapper xcxActivityMapper;
    @Value("${jutuike.youxuan}")
    private String youxuan;
    @Value("${jutuike.act}")
    private String actUrl;
    @Autowired
    private SysUserService sysUserService;
    @Resource
    private XcxPromotionMapper xcxPromotionMapper;

    @Override
    public XcxGetPromotionVO getPromotion(Integer platform, Integer actId) {
        // 获取用户UID 此处如果是饿了么平台活动的话 由于聚推客限制每个用户只有20个自定义ID，所以我们不做饿了么的返利了，统一使用 000000 为UID进行生成活动
        String uid = platform.equals(ActivityPlatformEnum.ELM.getCode()) ? CommonConstant.UID : ThreadLocalUtils.get().getUid();

        XcxPromotion promotion = xcxPromotionMapper.selectOne(new QueryWrapper<XcxPromotion>()
                .eq("uid", uid)
                .eq("act_id", actId));
        // 如果查询不到活动推广信息,则需要生成
        if (ObjectUtils.isEmpty(promotion)) {
            ExecutorService executorService = ThreadPoolUtils.getExecutorService();
            ActGenerateCallable actGenerateCallables = new ActGenerateCallable(sysUserService.getSysUser().getApiKey(), platform, actId, uid, actUrl);
            try {
                Future<XcxPromotion> future = executorService.submit(actGenerateCallables);
                promotion = future.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
            xcxPromotionMapper.insert(promotion);
        }
        return JSON.parseObject(JSON.toJSONString(promotion), XcxGetPromotionVO.class);
    }

    @Override
    public List<XcxGetMtYouXuanResp> mtYouXuan(XcxGetMtYouXuanDTO data) {

        Map<String, Object> param = new HashMap<>();
        param.put("apikey", sysUserService.getSysUser().getApiKey());
        param.put("sid", ThreadLocalUtils.get().getUid());
        param.put("pageNO", data.getPageNO());
        param.put("pageSize", data.getPageSize());
        param.put("longitude", data.getLongitude());
        param.put("latitude", data.getLatitude());
        param.put("relation_flag_name", CommonConstant.RELATION_FLAG_NAME);

        String resp = HttpClientUtils.doPost(youxuan, JSON.toJSONString(param));
        JSONObject jsonObject = JSON.parseObject(resp);

        Object dataObj = jsonObject.get("data");
        if (!jsonObject.get("code").equals(1) || ObjectUtils.isEmpty(dataObj)) {
            return null;
        }
        Object skuList = JSON.parseObject(JSON.toJSONString(dataObj)).get("skuList");
        if (ObjectUtils.isEmpty(skuList)) {
            return null;
        }
        return JSON.parseArray(JSON.toJSONString(skuList), XcxGetMtYouXuanResp.class);
    }
}
